<?php

class AppsWebModule extends WebModule {
    protected $id = 'apps';
    protected $appGroups;

    ////// inherited and conventional module functions

    public function getAppGroups() {
        return $this->getModuleSections('appgroups');
    }

    protected function getModuleAdminSections() {
        $sections = parent::getModuleAdminSections();

        foreach ($this->getAppGroups() as $appgroup=>$data) {
            $sections['apps-'.$appgroup] = array(
                'title'=>$data['title'],
                'type'=>'module hidden'
            );
        }

        return $sections;
    }

    protected function getModuleAdminConfig() {
        $configData = parent::getModuleAdminConfig();

        foreach ($this->getAppGroups() as $appgroup=>$data) {
            $appData = $configData['app'];
            $appData['title'] = $data['title'];
            $appData['config'] = 'apps-' . $appgroup;
            $appData['configMode'] = Config::OPTION_CREATE_EMPTY;
            $configData['apps-'.$appgroup] = $appData;
        }
        unset($configData['app']);

        return $configData;
    }

    public function getAppsForGroup($group=null) {
        $file = 'apps-' . $group;
        $filePath = SITE_CONFIG_DIR . DIRECTORY_SEPARATOR . $this->getConfigModule() . DIRECTORY_SEPARATOR . $file . '.ini';

        if (file_exists($filePath))
            return $this->getModuleSections($file);
        else
            return false;
    }
    
    protected function getAppData($group=null) {
        $apps = $this->getAppsForGroup($group);
                
        foreach ($apps as &$app) {
            if (isset($app['icon']) && strlen($app['icon'])) {
                $app['img'] = "/modules/{$this->configModule}/images/{$app['icon']}{$this->imageExt}";
            }
        }
        
        return $apps;
    }

    protected function initializeForPage() {
        $apps = $this->getAppData($this->platform);

        $this->assign('deviceName', Kurogo::getOptionalSiteVar($this->platform, null, 'deviceNames'));

        $this->assign('description', $this->getOptionalModuleVar('description','', 'strings'));
        $this->assign('description_footer', $this->getOptionalModuleVar('description_footer','', 'strings'));
        $this->assign('displayType', $this->getModuleVar('display_type'));
        $this->assign('apps',  $apps);
    }
}
